﻿using System;
using System.Collections.Generic;
using System.Linq;
using BonsaiScrum.Bus;
using BonsaiScrum.Core.Command;
using BonsaiScrum.Core.CommandHandlers;

namespace BonsaiScrum.Mvc.Configuration
{
    internal class CommandHandlerHelper
    {
        public static IDictionary<Type, IList<Type>> GetCommandHandlers()
        {
            IDictionary<Type, IList<Type>> commands = new Dictionary<Type, IList<Type>>();

            typeof(CreateNewProjectHandler)
                .Assembly
                .GetExportedTypes()
                .Where(x => x.GetInterfaces().Any(y => y.IsGenericType && y.GetGenericTypeDefinition() == typeof(ICommandHandler<>)))
                .ToList()
                .ForEach(x => AddItem(commands, x));

            return commands;
        }

        public static IEnumerable<Type> GetCommands()
        {
            var commands = new List<Type>();

            return
                typeof(CreateNewProject)
                .Assembly
                .GetExportedTypes()
                .Where(x => x.IsClass && x.GetInterfaces().Contains(typeof(ICommand)))
                .ToList();
        }

        private static void AddItem(IDictionary<Type, IList<Type>> commands, Type type)
        {
            var command = type.GetInterfaces()
                .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICommandHandler<>))
                .First()
                .GetGenericArguments()
                .First();

            if (!commands.ContainsKey(command))
                commands.Add(command, new List<Type>());

            commands[command].Add(type);
        }
    }
}
